package org.zjvis.datascience.common.util;

import java.text.DecimalFormat;

/**
 * @description 数据量大小转换工具类
 * @date 2021-05-31
 */
public class ConvertByteUtil {
    public static final long kb = 1024;
    public static final long mb = kb * 1024;
    public static final long gb = mb * 1024;

    public static Long convertLong(String num) {
        String[] num_split = num.split(" ");
        Long res = 0L;
        if ("bytes".equals(num_split[1])) {
            res = Long.parseLong(num_split[0]);
        } else if ("kB".equals(num_split[1])) {
            res = Long.parseLong(num_split[0]) * kb;
        } else if ("MB".equals(num_split[1])) {
            res = Long.parseLong(num_split[0]) * mb;
        } else if ("GB".equals(num_split[1])) {
            res = Long.parseLong(num_split[0]) * gb;
        }
        return res;
    }

    public static String convertBytes(Long num) {
        /*实现保留小数点两位*/
        DecimalFormat df = new DecimalFormat("#.00");
        String result;
        if (num >= gb) {
            result = df.format(num / gb) + " GB";
        } else if (num >= mb) {
            result = df.format(num / mb) + " MB";
        } else if (num >= kb) {
            result = df.format(num / kb) + " kB";
        } else {
            result = num + " bytes";
        }
        return result;
    }
}
